<template>
  <div id="DataMaintenance-ClientType">
    <div class="flex-all pt10 pb10 pl12 pr12 bg-white height50">
      <div class="ct-head-left flex-al">
        <span class="left-line-orange mr10"></span>
        <span class="color-333 fs14">客户标签</span>
      </div>
      <div class="cr-head-right">
        <el-button type="primary" size="mini" @click="handAdd">{{
          $t("enrollStudentSet.enrollStuSettings.ClientType.50zg4h5diyk0")
        }}</el-button>
      </div>
    </div>
    <div class="pAll12 bt_EBEEF5">
      <div class="flex-al Inquire-box mb12">
        <div class="ipt-box" style="width: 250px">
          <el-input
            v-model="filter.keyword"
            clearable
            placeholder="可检索标签类型名称"
            @clear="search"
            @keyup.enter.native="search"
          ></el-input>
        </div>
        <el-button
          type="primary"
          size="mini"
          class="search-btn fs14"
          @click="search"
          >{{
            $t("enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dljc0")
          }}</el-button
        >
      </div>
      <div class="tableDiv" ref="auto_height_table">
        <settingTableCont
          :tableData="tableList"
          @handleColumnChange="handleColumnChange"
        >
          <!-- 按钮操作组********start -->
          <el-table-column
            ref="fixedColumn"
            :label="
              $t('enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dm9c0')
            "
            align="center"
            width="120px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native.prevent="handEdit(scope.row)"
                >{{
                  $t(
                    "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dmm00"
                  )
                }}</el-button
              >
              <el-button
                type="text"
                size="small"
                @click.native.prevent="handDelete(scope.row)"
                >{{
                  $t(
                    "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dmx40"
                  )
                }}</el-button
              >
            </template>
          </el-table-column>
          <!-- 按钮操作组********end -->
        </settingTableCont>
        <!-- 分页 -->
        <el-pagination
          style="margin: 10px"
          :current-page.sync="paging.curPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size.sync="paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.pageTotal"
          @current-change="curPageChange"
          @size-change="pageSizeChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 侧边弹窗******新增或者编辑名单类型 -->
    <el-drawer
      :title="isEdit ? '编辑客户标签' : '新增客户标签'"
      :visible.sync="cancelVisible"
      direction="rtl"
      size="600px"
      :modal="false"
      custom-class="pop-slider--box"
      :before-close="handleClose"
    >
      <div class="slider-btn">
        <el-button
          v-if="!isEdit"
          type="primary"
          size="mini"
          @click="onSubmit"
          >{{
            $t("enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dn7w0")
          }}</el-button
        >
        <el-button v-else type="primary" size="mini" @click="onEditSubmit">{{
          $t("enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dn7w0")
        }}</el-button>
      </div>
      <div class="slider-content pAll20">
        <el-form
          label-width="130px"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
        >
          <el-form-item
            prop="labeltype_name"
            label="标签类型名称："
            :rules="[
              { required: true, message: '请输入标签类型 例如：意向度' },
              {
                min: 2,
                max: 6,
                message: '长度在2到6个字符',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              clearable
              :disabled="isEdit && ruleForm.is_use"
              placeholder="请输入标签类型名称"
              v-model="ruleForm.labeltype_name"
              style="width: 320px"
            ></el-input>
            <span v-if="isEdit && ruleForm.is_use" class="useMark fs14"
              >已使用</span
            >
          </el-form-item>
          <div class="labelName-list">
            <el-form-item
              v-for="(item, index) in ruleForm.labelNameList"
              :key="index"
              :prop="'labelNameList.' + index + '.label_name'"
              :label="index == 0 ? '标签名称：' : ''"
              :rules="[
                {
                  required: true,
                  trigger: ['blur'],
                  message: '标签名称不能为空',
                },
                {
                  min: 2,
                  max: 6,
                  message: '长度在2到6个字符',
                  trigger: ['blur'],
                },
                {
                  required: true,
                  trigger: ['blur'],
                  validator: checkPhone,
                },
              ]"
            >
              <el-input
                clearable
                :disabled="isEdit && item.is_use"
                :placeholder="
                  index == 0 ? '请输入标签名称 例如：有意向' : '请输入标签名称'
                "
                v-model="item.label_name"
                style="width: 320px"
              ></el-input>
              <template v-if="isEdit && item.is_use">
                <i
                  v-if="index == 0"
                  @click="addLabelName"
                  class="el-icon-circle-plus-outline icon-add"
                ></i>
                <span
                  :class="{ 'max-userMark': index == 0 }"
                  class="useMark fs14"
                  >已使用</span
                >
              </template>
              <template v-else>
                <template v-if="isEdit">
                  <i
                    v-if="index == 0"
                    @click="addLabelName"
                    class="el-icon-circle-plus-outline icon-add"
                  ></i>
                  <i
                    v-else
                    @click="deleteLabelName(index)"
                    class="el-icon-remove-outline icon-remove"
                  ></i>
                </template>
                <template v-else>
                  <i
                    v-if="index == 0"
                    @click="addLabelName"
                    class="el-icon-circle-plus-outline icon-add"
                  ></i>
                  <i
                    v-else
                    @click="deleteLabelName(index)"
                    class="el-icon-remove-outline icon-remove"
                  ></i>
                </template>
              </template>
            </el-form-item>
          </div>

          <p class="color-red">
            *
            {{
              $t("enrollStudentSet.enrollStuSettings.ClientType.50zg4h5doyk0")
            }}
          </p>
        </el-form>
      </div>
    </el-drawer>
    <!-- 删除名单类型 -->
    <popTips
      :dialogVisable="delItem"
      :popTipsCont="popTips_del"
      @handConfirm="delLabelTypeAction"
      @handCancel="delItem = false"
      @handleCloseTip="delItem = false"
    ></popTips>

    <popTips
      :dialogVisable="detailVisible"
      :popTipsCont="detailContent"
      @handCancel="detailVisible = false"
      @handleCloseTip="detailVisible = false"
    >
      <template slot="content">
        <settingTableCont
          :tableData="detailContent.tableData"
        ></settingTableCont>
      </template>
    </popTips>
  </div>
</template>

<script>
import settingTableCont from "@/components/tables/settingTableCont.vue";
import popTips from "@/components/common/popTips/popTips.vue";
import setHttp from "../../Set";

export default {
  name: "setting",
  components: {
    settingTableCont,
    popTips,
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      let labelId;
      this.ruleForm.labelNameList.forEach((v) => {
        if (v.label_name == value) {
          labelId = v.label_id;
        }
      });
      setHttp
        .checkRepeatLabelApi({
          label_name: value,
          label_id: labelId,
        })
        .then((res) => {
          const { error, errortip } = res.data;
          if (error == 1) {
            return callback(new Error(errortip));
          } else {
            callback();
          }
        });
    };
    return {
      checkPhone,
      delItem: false, //删除名单类型
      cancelVisible: false, //新增或者编辑名单类型
      isEdit: false, //是否编辑名单类型
      labelTypeId: "",
      //删除名单类型****弹窗
      popTips_del: {
        btn_text1: this.$t(
          "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dpbk0"
        ),
        btn_text2: this.$t(
          "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dpw00"
        ),
        title: "删除标签类型",
        context: this.$t(
          "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dqn40"
        ),
      },

      detailVisible: false,
      detailContent: {
        title: "标签类型明细",
        content: "",
        btn_text1: "",
        btn_text2: "",
        tableData: {
          // 表格的列
          columns: [],
          // 表格数据
          list: [],
          options: {
            errortip: "", //空页面提示内容
            mutiSelect: false, //是否显示多选
            issetting: false, //是否可以编辑列
          },
        },
      },

      //筛选
      filter: {
        keyword: "",
      },
      // 表格数据
      tableList: {
        // 表格的列
        columns: [],
        // 表格数据
        list: [],
        options: {
          errortip: "", //空页面提示内容
          mutiSelect: false, //是否显示多选
          issetting: false, //是否可以编辑列
          tableHeight: 0,
        },
      },
      // 分页
      paging: {
        curPage: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      // 表单
      ruleForm: {
        labeltype_name: "",
        labelNameList: [
          {
            label_name: "",
          },
        ], //标签名称列表
      },
      // 表单验证
      rules: {
        labeltype_name: [
          {
            required: true,
            message: this.$t(
              "enrollStudentSet.enrollStuSettings.ClientType.50zg4h5dqz80"
            ),
            trigger: "blur",
          },
          { min: 2, max: 16, message: "长度在2到16个字符", trigger: "blur" },
        ],
        clienttype_remk: [
          {
            required: false,
            message: "",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.labelType();
  },
  methods: {
    handleColumnChange(k, v, column) {
      console.log(column);
      this.detailContent.tableData.columns = [
        {
          custom: "1",
          fieldname: "标签名称",
          fieldstring: "label_name",
          show: "1",
        },
      ];
      if (column.label && column.label.length > 0) {
        this.detailContent.tableData.list = [...column.label];
      } else {
        this.detailContent.tableData.list = [];
        this.detailContent.tableData.options.errortip = "暂无标签类型明细～";
      }
      this.detailVisible = true;
    },
    // 添加标签名称
    addLabelName() {
      this.ruleForm.labelNameList.push({
        label_name: "",
      });
    },
     //删除标签名称
    deleteLabelName(k) {
      this.ruleForm.labelNameList.splice(k, 1);
    },
    // 招生相关设置->获取名单类型列表 -- wgh
    labelType() {
      setHttp
        .labelType({
          is_count: "1", //是否需要总数，可以不传
          p: this.paging.curPage,
          num: this.paging.pageSize,
          //筛选条件
          keyword: this.filter.keyword,
        })
        .then((res) => {
          const { error, errortip, result } = res.data;
          const { field, list, allnum } = result;
          this.paging.pageTotal = parseInt(allnum);
          this.tableList.columns = field;
          if (error == 0) {
            this.tableList.list = list;
          } else {
            this.tableList.list = [];
            this.tableList.options.errortip = errortip;
          }
        });
    },

    //检索
    search() {
      this.paging.curPage = 1;
      this.labelType();
    },
    //新增
    handAdd() {
      this.isEdit = false;
      this.cancelVisible = !this.cancelVisible;
      this.resetForm("ruleForm");
    },
    //编辑
    handEdit(v) {
      this.labelTypeId = v.labeltype_id;

      if (this.$refs["formData"]) {
        this.$refs["formData"].resetFields();
      }

      this.rowInfo = v;
      this.ruleForm = {
        labeltype_name: this.rowInfo.labeltype_name, //标签类型名称
        is_use: this.rowInfo.is_use,
        labelNameList: [...this.rowInfo.label], //标签名称列表
      };
      this.isEdit = true;
      this.cancelVisible = !this.cancelVisible;
    },
    //删除
    handDelete(row) {
      this.labelTypeId = row.labeltype_id;
      this.delItem = !this.delItem;
    },
    //招生相关设置->删除名单类型 -- wgh
    delLabelTypeAction() {
      setHttp
        .delLabelTypeAction({
          labeltype_id: this.labelTypeId,
        })
        .then((res) => {
          console.log(res);
          if (res.data.error == 0) {
            this.$message({ message: res.data.errortip, type: "success" });
            this.delItem = false;
            this.labelType();
          } else {
            this.$message.error(res.data.errortip);
          }
        });
    },
    //判断数组是否重复
    isRepeat(arr, name) {
      var hash = {};
      for (var i in arr) {
        if (hash[arr[i][name]]) return true;
        hash[arr[i][name]] = true;
      }
      return false;
    },
    //侧边弹窗 - 新增 - 提交
    onSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let label_list = [];
          this.ruleForm.labelNameList.forEach((e) => {
            label_list.push({
              label_name: e.label_name,
            });
          });
          if (this.isRepeat(label_list, "label_name")) {
            this.$message.error("存在标签名称重复");
          } else {
            setHttp
              .addLabelTypeAction({
                labeltype_name: this.ruleForm.labeltype_name,
                label_list: JSON.stringify(label_list),
              })
              .then((res) => {
                if (res.data.error == 0) {
                  this.$message({
                    message: res.data.errortip,
                    type: "success",
                  });
                  this.cancelVisible = false;
                  this.labelType();
                } else {
                  this.$message.error(res.data.errortip);
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    //侧边弹窗 - 编辑 - 提交
    onEditSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let label_list = [];
          this.ruleForm.labelNameList.forEach((e) => {
            if (!e.is_use) {
              label_list.push({
                label_name: e.label_name,
              });
            }
          });
          if (this.isRepeat(label_list, "label_name")) {
            this.$message.error("存在标签名称重复");
          } else {
            setHttp
              .updateLabelTypeAction({
                labeltype_id: this.labelTypeId,
                labeltype_name: this.ruleForm.labeltype_name,
                label_list: JSON.stringify(label_list),
              })
              .then((res) => {
                console.log(res);
                if (res.data.error == 0) {
                  this.$message({
                    message: res.data.errortip,
                    type: "success",
                  });
                  this.cancelVisible = false;
                  this.labelType();
                } else {
                  this.$message.error(res.data.errortip);
                }
              });
          }
        }
      });
    },
    // 复选框
    handleSelectionChange(v) {
      console.log(v);
    },
    // 页码变化
    curPageChange(v) {
      this.paging.curPage = v;
      this.labelType();
    },
    // pageSize改变
    pageSizeChange() {
      this.paging.curPage = 1;
      this.labelType();
    },
    // 重置表单
    resetForm(form) {
      this.ruleForm = {
        labeltype_name: "", //标签类型名称
        labelNameList: [
          {
            label_name: "",
          },
        ], //标签名称列表
      };
      if (this.$refs[form]) {
        this.$refs[form].resetFields();
      }
    },
    //侧边弹窗-关闭
    handleClose(done) {
      done();
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs["auto_height_table"]) {
        this.tableList.options.tableHeight = this.$Tool.getTableHeight(
          this.$refs.auto_height_table.getBoundingClientRect().top + 55
        );
      }
    });
  },
};
</script>

<style lang="less" scoped>
.labelName-list {
  .icon-add,
  .icon-remove {
    font-size: 24px;
    margin-left: 12px;
    vertical-align: middle;
    cursor: pointer;
    &.icon-add {
      color: #f78f0e;
    }
    &.icon-remove {
      color: red;
    }
  }
}
form {
  .useMark {
    color: #aaaaaa;
    margin-left: 48px;
    &.max-userMark {
      margin-left: 12px;
    }
  }
}
</style>
